package arrays;
import java.util.*;
/**
 * Created with IntelliJ IDEA.
 * Description: 977.有序数组的平方
 * User: Li_yizYa
 * Date: 2025—03—20
 * Time: 20:20
 */
public class Solution3 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("请输入要处理的数组大小: ");
        int n = scan.nextInt();
        int[] nums = new int[n];
        System.out.print("请输入数组元素: ");
        for (int i = 0; i < nums.length; i++) {
            nums[i] = scan.nextInt();
        }
        nums = sortedSquare(nums);
        System.out.print("处理后的数组为: ");
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }
    private static int[] sortedSquare(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }
        int left = 0;
        int right = nums.length - 1;
        int[] ret = new int[nums.length];
        int index = nums.length - 1;
        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] * nums[right]) {
                ret[index--] = nums[left] * nums[left];
                left++;
            } else {
                ret[index--] = nums[right] * nums[right];
                right--;
            }
        }
        return ret;
    }
}
